<?php

namespace App\Library;

use App\Jobs\Notification;

trait Json
{

    /**
     * 返回正常的数据
     * @param $code
     * @param string $msg
     * @return \Illuminate\Http\JsonResponse
     */
    public function jsonData($code, $msg = '')
    {
        $request['Ret'] = $code;
        $request['Msg'] = $msg;
        return response()->json($request);

    }

    /**
     * 返回json格式
     * @param $params
     * @return \Illuminate\Http\JsonResponse
     */
    public function json($params, $action = ''): \Illuminate\Http\JsonResponse
    {
        $operatorPriv = $this->getIvData($this->myOperatorID);
        if (!empty($params['OperatorID'])) {
            unset($params['OperatorID']);
        }
        $data = EncryptDecrypt::encrypt(json_encode($params), $operatorPriv['DataSecret'], $operatorPriv['DataSecretIV']);
        //签名
        $sigStr = sprintf("%s%s%s%s", $this->myOperatorID, $data, date('YmdHis'), "0001");
        $sig = HMACMD5::generate($operatorPriv['SigSecret'], $sigStr);
        //请求体
        $request = [
            'Msg' => "",
            'Data' => $data,
            'Ret' => 0,
            'Sig' => $sig
        ];
        if ($action) {
            //推送给第三方的格式1
            $notificationData = [
                'OperatorID' => $this->myOperatorID,
                'Data' => $data,
                'Seq' => "0001",
                'ConnectorID' => (string)$params['ConnectorID'],
                'TimeStamp' => date('YmdHis'),
                'action' => $action,
                'StartChargeSeq' => $params['StartChargeSeq'],
                'Sig' => $sig
            ];
            Notification::dispatch($notificationData);
        }
        return response()->json($request);
    }
}
